package com.example.tsbs.controller;

import com.example.tsbs.config.Result;
import com.example.tsbs.util.FileUtil;
import com.example.tsbs.util.UseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

@Slf4j
@Api(tags="功能测试")
@RestController
@RequestMapping("/api")
public class FunctionTest {

    @ApiOperation("查看文件是否存在")
    @PostMapping("/getFileIsExit")
    public String getFileIsExit(@Parameter(description = "文件路径(包含文件名)")@RequestParam(value = "path")String path) {
        String result = "";
        boolean isExit = FileUtil.isFileExist(path);
        if(isExit) {
            result = path+"文件存在";
        } else {
            result = path+"文件不存在";
        }
        return result;
    }

    @ApiOperation("中文文件重命名")
    @PostMapping("/renameFile")
    public String renameFile(@Parameter(description = "文件路径(包含文件名)")@RequestParam(value = "path")String path) {
        String result = "";
        result = FileUtil.renameFile(path);
        return result;
    }

    @ApiOperation("Docker可执行文件测试")
    @PostMapping("/getDockerTask")
    public String getDockerTask() {
        String result = "";
        String containerId = "afc89852df43";
        String filePath = "/root/run/data.json";
        if(!FileUtil.checkDockerFile(containerId, filePath)) {
            return "docker容器"+containerId+"中"+filePath+"不存在";
        }
        String[] commands = {"docker", "exec", "-w", "/root/run", "ubuntu2", "./genGeoModel", "data.json"};
        UseUtil.execDockerCommand(commands);
        return result;
    }
    @ApiOperation("Docker结果文件复制测试")
    @PostMapping("/getDockerCopyTask")
    public String getDockerCopyTask() {
        String result = "";
        String containerId = "afc89852df43";
        String sourcePath = "/root/run/测试文件.igs";
        String destinationPath = "/root";
        if(!FileUtil.checkDockerFile(containerId, sourcePath)) {
            return "docker容器"+containerId+"中"+sourcePath+"不存在";
        }
        String[] commands = {"docker", "cp", containerId + ":" + sourcePath, destinationPath};
        UseUtil.execDockerCommand(commands);
        return result;
    }

    @ApiOperation("绝对路径的BP的freq_cal可执行文件测试")
    @PostMapping("/getSubBPTask")
    public String getSubBPTask() {
        String calFileName = "/root/tsbsDuiJie/ts/freq_cal";//频域可执行文件freq_cal的路径
        String jsonFileName = "/root/tsbsDuiJie/ts/freq.json";//可执行文件调用的json文件路径
            // 目标目录
            String directory = "/root/tsbsDuiJie/ts";

        String exeFilePath = calFileName;
        String jsonFilePath = jsonFileName;
        Integer poolSize = 4;
        Integer poolIndex = 0;

        log.info("调用可执行文件"+exeFilePath);
        String result = "";
        String exePath = exeFilePath;
        String jsonPath = jsonFilePath;
        String runNumber = String.valueOf(poolSize);
        String index = String.valueOf(poolIndex);
        if(!FileUtil.isFileExist(exePath)) {
            log.info(exePath+"文件不存在");
            return exePath+"文件不存在";
        }
        if(!FileUtil.isFileExist(jsonPath)) {
            log.info(jsonPath+"文件不存在");
            return jsonPath+"文件不存在";
        }
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new java.io.File(directory));
        processBuilder.command(exePath, jsonPath, runNumber,index);
        try {
            String[] commands = new String[]{exePath, jsonPath, runNumber,index};
            log.info("可执行程序开始运行,运行参数："+ Arrays.toString(commands));

            Process process = processBuilder.start();

            // 读取标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待程序执行完成
            process.waitFor();

            // 获取退出值
            int exitValue = process.exitValue();
            log.info("线程池第"+(poolIndex+1)+"个线程运行完毕，"+"值为：: " + exitValue);

            if(exitValue == 0) {
                result = "成功";
            } else {
                result = "线程运行失败";
            }
        } catch (IOException | InterruptedException e) {
            log.info(exeFilePath+"运行失败");
            result = "线程运行失败";
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation("绝对路径的BS的time_cal可执行文件测试")
    @PostMapping("/getSubBSTTask")
    public String getSubBSTTask() {
        String calTimeFileName = "/root/tsbsDuiJie/time_light/time_cal";//频域可执行文件time_cal的路径
        String calLightFileName = "/root/tsbsDuiJie/time_light/light_cal";//频域可执行文件light_cal的路径
        String jsonFileName = "/root/tsbsDuiJie/time_light/time_light.json";//可执行文件调用的json文件路径
        String directory = "/root/tsbsDuiJie/time_light";
        String exeFilePath = calTimeFileName;
        String jsonFilePath = jsonFileName;
        Integer poolSize = 4;
        Integer poolIndex = 0;

        log.info("调用可执行文件"+exeFilePath);
        String result = "";
        String exePath = exeFilePath;
        String jsonPath = jsonFilePath;
        String runNumber = String.valueOf(poolSize);
        String index = String.valueOf(poolIndex);
        if(!FileUtil.isFileExist(exePath)) {
            log.info(exePath+"文件不存在");
            return exePath+"文件不存在";
        }
        if(!FileUtil.isFileExist(jsonPath)) {
            log.info(jsonPath+"文件不存在");
            return jsonPath+"文件不存在";
        }
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new java.io.File(directory));
        processBuilder.command(exePath, jsonPath, runNumber,index);
        try {
            String[] commands = new String[]{exePath, jsonPath, runNumber,index};
            log.info("可执行程序开始运行,运行参数："+ Arrays.toString(commands));
            Process process = processBuilder.start();

            // 读取标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待程序执行完成
            process.waitFor();

            // 获取退出值
            int exitValue = process.exitValue();
            log.info("线程池第"+(poolIndex+1)+"个线程运行完毕，"+"值为：: " + exitValue);

            if(exitValue == 0) {
                result = "成功";
            } else {
                result = "线程运行失败";
            }
        } catch (IOException | InterruptedException e) {
            log.info(exeFilePath+"运行失败");
            result = "线程运行失败";
            e.printStackTrace();
        }
        return result;
    }
    @ApiOperation("绝对路径的BS的light_cal可执行文件测试")
    @PostMapping("/getSubBSLTask")
    public String getSubBSLTask() {
        String calTimeFileName = "/root/tsbsDuiJie/time_light/time_cal";//频域可执行文件time_cal的路径
        String calLightFileName = "/root/tsbsDuiJie/time_light/light_cal";//频域可执行文件light_cal的路径
        String jsonFileName = "/root/tsbsDuiJie/time_light/time_light.json";//可执行文件调用的json文件路径
        String directory = "/root/tsbsDuiJie/time_light";
        String exeFilePath = calLightFileName;
        String jsonFilePath = jsonFileName;
        Integer poolSize = 4;
        Integer poolIndex = 0;

        log.info("调用可执行文件"+exeFilePath);
        String result = "";
        String exePath = exeFilePath;
        String jsonPath = jsonFilePath;
        String runNumber = String.valueOf(poolSize);
        String index = String.valueOf(poolIndex);
        if(!FileUtil.isFileExist(exePath)) {
            log.info(exePath+"文件不存在");
            return exePath+"文件不存在";
        }
        if(!FileUtil.isFileExist(jsonPath)) {
            log.info(jsonPath+"文件不存在");
            return jsonPath+"文件不存在";
        }
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new java.io.File(directory));
        processBuilder.command(exePath, jsonPath, runNumber,index);
        try {
            log.info(exeFilePath+"运行开始");
            Process process = processBuilder.start();

            // 读取标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待程序执行完成
            process.waitFor();

            // 获取退出值
            int exitValue = process.exitValue();
            log.info("线程池第"+(poolIndex+1)+"个线程运行完毕，"+"值为：: " + exitValue);

            if(exitValue == 0) {
                result = "成功";
            } else {
                result = "线程运行失败";
            }
        } catch (IOException | InterruptedException e) {
            log.info(exeFilePath+"运行失败");
            result = "线程运行失败";
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation("绝对路径的MZ可执行文件测试")
    @PostMapping("/getSubMZTask")
    public Result<?> getSubMZTask(@Parameter(description = "exeFilePath")@RequestParam(value = "exeFilePath")String exeFilePath,
                                  @Parameter(description = "jsonFilePath")@RequestParam(value = "jsonFilePath")String jsonFilePath) {
        String result = "";
        String exePath = exeFilePath;
        String jsonPath = jsonFilePath;
        String type = "MZ";
        if(FileUtil.isFileExist(exePath)) {
            result = exePath+"文件不存在";
            return Result.success(result);
        }
        if(FileUtil.isFileExist(jsonPath)) {
            result = jsonPath+"文件不存在";
            return Result.success(result);
        }
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(exePath, jsonPath);
        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            // 读取标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待程序执行完成
            process.waitFor();
            // 获取退出值
            int exitValue = process.exitValue();
            if(exitValue == 0) {
                result = "成功";
            } else {
                result = "线程运行失败";
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return Result.success(result);
    }

}
